package LeetCode.leetcode110;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null)
            return true;
        int l = maxLength(root.left);
        int r = maxLength(root.right);
        if (Math.abs(l - r) > 1) {
            return false;
        } else {
            boolean left = isBalanced(root.left);
            boolean right = isBalanced(root.right);
            return left & right;
        }
    }

    public static int maxLength(TreeNode node) {
        if (node == null)
            return 0;
        int leftLength = maxLength(node.left);
        int rightLength = maxLength(node.right);
        return Math.max(leftLength, rightLength) + 1;
    }
}
